﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ELearning.API.Controllers.AzureControllers;
using ELearning.BLL;
using ELearning.Common.CommonStr;
using ELearning.Common.Model;
using ELearning.Models.ViewModel.CourseSeries;

namespace ConsoleJobs.Jobs
{
    public static class ConvertVideoJob
    {
        private static ECourseSeriesService ECourseSeriesService = new ECourseSeriesService();

        private static EAttachmentService attachmentService = new EAttachmentService();

        private static EMessageLogService messageLogService => new EMessageLogService();

        /// <summary>
        /// 把转码中的视频地址获取到
        /// </summary>
        public static ServiceResponse<GetVideoUrlViewModel> GetVideoUrl()
        {
            var viewModel = new GetVideoUrlViewModel();
            //var modelList = ECourseSeriesService.FindList(c => !c.IsDelete && c.EncodeState.Equals(0) && c.ParentCSID == Guid.Empty).ToList();
            //var ids = modelList.Select(m => m.ID).ToList();
            //var chapterList = ECourseSeriesService.GetCourseSeriesByIds(ids);
            List<ChapterItem> children = new List<ChapterItem>();
            GetChapterList(children);
            return ServiceResponse<GetVideoUrlViewModel>.SuccessResponse("success", viewModel);
        }

        private static void GetChapterList(List<ChapterItem> children)
        {
            var allWareList = ECourseSeriesService.FindList(c => !c.IsDelete && c.NodeLevel == 5).ToList();
            var modelList = ECourseSeriesService.FindList(c => !c.IsDelete).ToList();
            var cIds = allWareList.Select(c => c.ID).ToList();
            var attachs = attachmentService.FindList(a => !a.IsDelete && cIds.Contains(a.TeachingID)).ToList();
            var ams = new AzureMediaServiceController();
            var cList = modelList.Where(c => c.ParentCSID == Guid.Empty).ToList();
            foreach (var course in cList)
            {
                var encoded = 0;//转码完成的数量
                var failencoded = 0;//转码失败的数量
                var allCount = 0;//课件总数量
                var sList = modelList.Where(c => c.ParentCSID == course.ID).ToList();
                foreach (var m in sList)  //章列表
                {
                    var v = new ChapterItem
                    {
                        ID = m.ID,
                        CoverUrl = m.CoverUrl,
                        ParentCSID = m.ParentCSID,
                        Description = m.Description,
                        title = m.Title,
                        NodeLevel = 2
                    };

                    //节
                    v.children = modelList.Where(c => c.ParentCSID == v.ID).Select(c => new ChapterItem
                    {
                        ID = c.ID,
                        CoverUrl = c.CoverUrl,
                        ParentCSID = c.ParentCSID,
                        Description = c.Description,
                        title = c.Title,
                        NodeLevel = 3
                    }).ToList();

                    foreach (var section in v.children)
                    {
                        //课时
                        section.children = modelList.Where(c => c.ParentCSID == section.ID).Select(c => new ChapterItem
                        {
                            ID = c.ID,
                            CoverUrl = c.CoverUrl,
                            ParentCSID = c.ParentCSID,
                            Description = c.Description,
                            title = c.Title,
                            NodeLevel = 4
                        }).ToList();

                        foreach (var hour in section.children)
                        {
                            var wareIds = modelList.Where(c => c.ParentCSID == hour.ID).Select(c => c.ID).ToList();
                            hour.files = attachs.Where(a => wareIds.Contains(a.TeachingID)).Select(c => new CourseFile()
                            {
                                fileUrl = c.AttachmentUrl,
                                DownloadUrl = c.DownloadUrl,
                                Description = c.Description,
                                Size = c.AttachmentSize,
                                filename = c.AttachmentName,
                                DisplayName = c.AttachmentDIsplayName,
                                icon = c.AttachmentExt,
                                ID = c.ID,
                                NodeLevel = 5,
                                Duration = c.Duration,
                                AssetId = c.AssetId,
                                JobId = c.JobId
                            }).ToList();

                            var codingList = attachs.Where(a => wareIds.Contains(a.TeachingID)).ToList();
                            if (codingList.Any())
                            {
                                foreach (var attachment in codingList)
                                {
                                    if (attachment.AttachmentExt == "mp4")
                                    {
                                        allCount++;
                                        string url = attachment.AttachmentUrl;
                                        if (!string.IsNullOrEmpty(url) && url != CommonConst.CourseProcessing && url != CommonConst.CourseFailed) //已经是转码成功的地址不需要获取一次
                                        {
                                            encoded++;
                                            continue;
                                        }

                                        try
                                        {
                                            url = ams.GetUrl(attachment.JobId);
                                        }
                                        catch (Exception e)
                                        {
                                            url = string.Empty;
                                        }
                                        if (url == CommonConst.CourseFailed)
                                            failencoded++;
                                        if (!string.IsNullOrEmpty(url) && url != CommonConst.CourseProcessing && url != CommonConst.CourseFailed)
                                            encoded++;
                                        attachment.AttachmentUrl = url;
                                        attachmentService.UpdateNoSaveChange(attachment);

                                    }
                                }
                            }
                        }
                    }

                    children.Add(v);
                }
                if (allCount == encoded)
                {
                    course.EncodeState = 1;
                }
                else if (allCount > encoded)
                {
                    course.EncodeState = 0;
                }
                if (allCount == 0)
                {
                    course.EncodeState = -1;
                }
                if (failencoded > 0)
                {
                    course.EncodeState = 2;
                }
                ECourseSeriesService.UpdateNoSaveChange(course);
            }
            ECourseSeriesService.SaveChange();
        }

    }
}
